package com.atguigu.day02;

import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink04_Runtime_Mode {
    public static void main(String[] args) throws Exception {
        //1.获取Flink 流 执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //将程序并行度设置为1
        env.setParallelism(1);

        //TODO 手动设置运行模式
//        env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);//自动
//        env.setRuntimeMode(RuntimeExecutionMode.BATCH);//批
        env.setRuntimeMode(RuntimeExecutionMode.STREAMING);//流

        //2.获取文件中的数据
        DataStreamSource<String> streamSource = env.readTextFile("input/word.txt");
//        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.将读过来的数据按照空格切分 切出每一个单词
        SingleOutputStreamOperator<String> wordDStream = streamSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        });

        //4.将每个单词组成Tuple二元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOneDStream = wordDStream.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return Tuple2.of(value, 1);
            }
        });

        //5.将相同的单词聚合到一块
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = wordToOneDStream.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            /**
             * 指定 key
             * @param value The object to get the key from.
             * @return
             * @throws Exception
             */
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                return value.f0;
            }
        });

        //6.做累加操作
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream.sum("f1");

        //7.将结果打印到控制台
        result.print();

        //8.执行
        JobExecutionResult execute = env.execute();
//        System.out.println(execute);
    }
}
